var express = require('express');
var session = require('express-session')
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

//++++++++++++++++++++++++++++++++++
var http = require('http').Server(app);
var io = require('socket.io')(http);

//在线用户
var onlineUser = {};
var onlineCount = 0;


io.on('connection', function (socket) {
    //监听新用户加入
    socket.on('login', function (obj) {
        socket.name = obj.username;
        //socket.id = obj.username;
        console.log('socket.id' + socket.id);
        onlineUser[socket.id] = obj.username;

        var roomid = obj.roomid;
        socket.leave(roomid, err => {
            console.log(err);
            socket.join(roomid);
            // if (!onlineUser.hasOwnProperty(obj.username)) {
            //     onlineUser[obj.username] = obj.username;
            //     //在线人数+1
            //     onlineCount++;
            // }
            //广播消息
            io.to(roomid).clients((error, clients) => {
                if (error) throw error;
                //socket.send("login", clients);
                var a = [];
                for (var i = 0; i < clients.length; i++) {
                    a.push({ id: clients[i], name: onlineUser[clients[i]] });
                }
                io.to(roomid).emit("clients", a);
                //console.log(obj.username + "加入了聊天室"+roomid);
            });
        });
    })

    //监听用户退出
    socket.on('logout', function (obj) {
        //socket.name = obj.username;
        var roomid = obj.roomid;
        socket.leave(roomid);
        io.to(roomid).clients((error, clients) => {
            if (error) throw error;
            var a = [];
            for (var i = 0; i < clients.length; i++) {
                a.push({ id: clients[i], name: onlineUser[clients[i]] });
            }
            io.to(roomid).emit("clients", a);
            //console.log(obj.username + "离开了聊天室");
        });
    })

    //监听新用户加入
    socket.on('clients', function (obj) {
        socket.name = obj.username;
        var roomid = obj.roomid;
        if (socket.rooms[obj.roomid]) {
            //向所有客户端广播发布的消息
            //io.emit('message', obj);

            io.to(roomid).clients((error, clients) => {
                if (error) throw error;
                var a = [];
                //socket.send("login", clients);
                for (var i = 0; i < clients.length; i++) {
                    a.push({ id: clients[i], name: onlineUser[clients[i]] });
                }
                io.to(roomid).emit("clients", a);
            });

        } else {
            //console.log(obj.username + '不在' + obj.roomid + '中，不能说查看群中用户');
        }
    })

    //监听用户发布聊天内容
    socket.on('message', function (obj) {
        if (socket.rooms[obj.roomid]) {
            io.to(obj.roomid).emit("message", obj);
            //向所有客户端广播发布的消息
            //io.emit('message', obj);
            //console.log(obj.username + '在' + obj.roomid + '中说：' + obj.content);
            
        } else {
            //console.log(obj.username + '不在' + obj.roomid + '中，不能说：' + obj.content);
        }
    });
});
http.listen(3001, function () {
    //console.log('listening on *:3001');
});
//-----------------------------


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


app.set('trust proxy', 1); // trust first proxy
app.use(session({
    secret: 's3Cur3',
    name: 'sessionId'
}));

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true  }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


// 无须权限

app.use('/login', require("./routes/login"));
//app.use('/login/submit', require("./routes/login"));

// catch 404 and forward to error handler
// app.use(function (req, res, next) {
//     if (req.session.user == null) {
//         console.log("用户未登陆");
//         res.redirect("/login");
//     }
// });

// 须要权限
app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
